Page({
  data: {
    carts: [],
    hasList: false,
    totalPrice: 0,
    selectAllStatus: true,
    obj: { name: "hello" }
  },

  // 获取许愿池商品信息
onShow() {
  let carts = wx.getStorageSync('cartItems') || [];
  this.setData({
      hasList: carts.length > 0,
      carts: carts
  });
  this.getTotalPrice();
},

// 结算按钮点击事件
checkout() {
  let selectedCarts = this.data.carts.filter(item => item.selected);
  wx.setStorageSync('selectedCarts', selectedCarts);
  wx.navigateTo({
      url: '../orders/orders'
  });
},

  selectList(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    const selected = carts[index].selected;
    carts[index].selected = !selected;
    this.setData({ carts });
    wx.setStorageSync('cartItems', carts);
    this.getTotalPrice();
  },

  deleteList(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    carts.splice(index, 1);
    this.setData({ carts });
    if (!carts.length) {
      this.setData({ hasList: false });
    }
    wx.setStorageSync('cartItems', carts);
    this.getTotalPrice();
  },

  selectAll(e) {
    let selectAllStatus = this.data.selectAllStatus;
    selectAllStatus = !selectAllStatus;
    let carts = this.data.carts;
    for (let i = 0; i < carts.length; i++) {
      carts[i].selected = selectAllStatus;
    }
    this.setData({ selectAllStatus, carts });
    wx.setStorageSync('cartItems', carts);
    this.getTotalPrice();
  },

  addCount(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    let num = carts[index].num;
    num++;
    carts[index].num = num;
    this.setData({ carts });
    wx.setStorageSync('cartItems', carts);
    this.getTotalPrice();
  },

  minusCount(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    let num = carts[index].num;
    if (num <= 1) return;
    num--;
    carts[index].num = num;
    this.setData({ carts });
    wx.setStorageSync('cartItems', carts);
    this.getTotalPrice();
  },

  getTotalPrice() {
    let carts = this.data.carts;
    let total = 0;
    for (let i = 0; i < carts.length; i++) {
      if (carts[i].selected) {
        total += carts[i].num * carts[i].price;
      }
    }
    this.setData({ totalPrice: total.toFixed(2) });
  },
});

